#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <string>
#include <unordered_map>

class DictServer 
{
public:
    DictServer(int port)
        :_server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), 
        "DictServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::onMessage, this, std::placeholders::_1,
                                    std::placeholders::_2,std::placeholders::_3));
    }

    void Start()
    {
        _server.start();  //先开始监听
        _baseloop.loop(); //开始死循环事件监控
    }
       
private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected())
        {
            std::cout << "连接建立！\n";
        }
        else
        {
            std::cout << "连接断开！\n";
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::unordered_map<std::string, std::string> dict_map = {
            {"hello",  "你好"},
            {"world",  "世界"},
            {"who",  "谁"},
            {"disapper", "消失"}
        };

        std::string msg = buf->retrieveAllAsString();
        std::string ret;
        auto iter = dict_map.find(msg);
        if(iter != dict_map.end())
        {
            ret = iter->second;
        }
        else
        {
            ret = "未知单词！";
        }

        conn->send(ret);
    }

       
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;

};

int main()
{
    DictServer dict(8080);
    dict.Start();
    
    return 0;
}
